package com.heima.article.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.article.mapper.ApArticleConfigMapper;
import com.heima.article.mapper.ApArticleContentMapper;
import com.heima.article.mapper.ApArticleMapper;
import com.heima.article.mapper.AuthorMapper;
import com.heima.article.service.ApArticleService;
import com.heima.article.service.GeneratePageService;
import com.heima.common.constants.message.ArticleConstants;
import com.heima.common.constants.wemedia.WemediaConstants;
import com.heima.common.exception.CustException;
import com.heima.feigns.AdminFeign;
import com.heima.feigns.WemediaFeign;
import com.heima.model.admin.pojos.AdChannel;
import com.heima.model.article.dtos.ArticleHomeDTO;
import com.heima.model.article.pojos.ApArticle;
import com.heima.model.article.pojos.ApArticleConfig;
import com.heima.model.article.pojos.ApArticleContent;
import com.heima.model.article.pojos.ApAuthor;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.pojos.WmNews;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;


@Service
@Slf4j
public class ApArticleServiceImpl extends ServiceImpl<ApArticleMapper, ApArticle> implements ApArticleService {

    @Autowired
    GeneratePageService generatePageService;
    @Transactional
    @Override
    //入参时自媒体文章的ID
    public void publishArticle(Integer newsId) {
        // 1.基于feign查询自媒体文章数据, 查询并检查自媒体文章  wmNews
        WmNews wmNews = getWmNews(newsId);
        // 2. 封装成ApArticle
        ApArticle apArticle = getApArticle(wmNews);
        // 3. 保存或修改文章(id)
        saveOrUpdateApArticle(apArticle);
        // 4. 保存关联配置和内容信息
        saveConfigAndContent(apArticle, wmNews);
        // 5. TODO 文章页面静态化
         generatePageService.generateArticlePage(wmNews.getContent(),apArticle);
        // 6. 修改 wmNews状态  改为9  并设置articleId
        wmNews.setStatus((short) 9);
        wmNews.setArticleId(apArticle.getId());
        ResponseResult newResult = wemediaFeign.updateWmNews(wmNews);
        if (newResult.getCode().intValue()!=0) {
            CustException.cust(AppHttpCodeEnum.REMOTE_SERVER_ERROR,"远程调用失败");
        }
        // 7. TODO 通知es索引库添加文章索引

    }

    //因为有多个写的方法,所以必须要加事务
    @Transactional
    public void saveConfigAndContent(ApArticle apArticle, WmNews wmNews) {
        //保存配置
        ApArticleConfig config = new ApArticleConfig();

        config.setArticleId(apArticle.getId());
        config.setIsComment(true);
        config.setIsForward(true);
        config.setIsDown(false);//上架
        config.setIsDelete(false);//没有被删除
        apArticleConfigMapper.insert(config);
        //保存文章内容
        ApArticleContent content = new ApArticleContent();
        content.setArticleId(apArticle.getId());
        content.setContent(wmNews.getContent());
        apArticleContentMapper.insert(content);

    }

    @Autowired
    ApArticleConfigMapper apArticleConfigMapper;

    @Autowired
    ApArticleContentMapper apArticleContentMapper;

    //保存或者修改文章
    private void saveOrUpdateApArticle(ApArticle apArticle) {
        if (apArticle.getId() == null) {
            //保存
            apArticle.setCollection(0);//代表这篇文章的收藏量
            apArticle.setComment(0);//代表评论数量
            apArticle.setLikes(0);//点赞数量
            apArticle.setViews(0);//代表阅读数量
            apArticle.setCreatedTime(new Date());
            save(apArticle);

        } else {
            //修改文章
            ApArticle byId = getById(apArticle.getId());
            if (byId == null) {
                CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST, "关联的文章信息不存在");
            }
            updateById(apArticle);
            //删除关联配置和内容信息
            apArticleContentMapper.delete(Wrappers.<ApArticleContent>lambdaQuery().eq(ApArticleContent::getArticleId, apArticle.getId()));
            apArticleConfigMapper.delete(Wrappers.<ApArticleConfig>lambdaQuery().eq(ApArticleConfig::getArticleId, apArticle.getId()));

        }


    }

    @Autowired
    AdminFeign adminFeign;

    @Autowired
    AuthorMapper authorMapper;

    private ApArticle getApArticle(WmNews wmNews) {
        ApArticle apArticle = new ApArticle();
        //属性拷贝,前面的拷贝到后面的
        BeanUtils.copyProperties(wmNews, apArticle);
        //设置文章ID
        apArticle.setId(wmNews.getArticleId());
        apArticle.setFlag((byte) 0);
        apArticle.setLayout(wmNews.getType());
        //频道信息
        ResponseResult<AdChannel> channelResult = adminFeign.findOne(wmNews.getChannelId());
        if (channelResult.getCode().intValue() != 0) {
            log.error(" 文章发布失败  原因:远程调用查询频道信息失败 {} ", channelResult.getErrorMessage());
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST, "未查询到自媒体文章!");
        }
        //得到自媒体文章的数据,再检查自媒体文章有没有
        AdChannel channel = channelResult.getData();
        if (wmNews == null) {
            log.error(" 文章发布失败  原因:未查到相关频道信息,文章id {} 频道id:{}", wmNews.getId(), wmNews.getChannelId());
            CustException.cust(AppHttpCodeEnum.REMOTE_SERVER_ERROR, "自媒体文章不存在,远程查询自媒体文章失败!");
        }
        apArticle.setChannelName(channel.getName());
        //作者信息
        //得到一个作者
        ApAuthor author = authorMapper.selectOne(Wrappers.<ApAuthor>lambdaQuery().eq(ApAuthor::getWmUserId, wmNews.getUserId()));
        if (author == null) {
            log.error(" 文章发布失败  原因:未查到相关作者信息,文章id {} 自媒体用户id:{}", wmNews.getId(), wmNews.getUserId());
            CustException.cust(AppHttpCodeEnum.REMOTE_SERVER_ERROR, "未查询到相关作者");
        }
        apArticle.setAuthorId(Long.valueOf(author.getId()));
        apArticle.setAuthorName(author.getName());

        return apArticle;
    }

    @Autowired
    WemediaFeign wemediaFeign;

    private WmNews getWmNews(Integer newsId) {
        //1.远程查询自媒体文章
        ResponseResult<WmNews> wmNewsById = wemediaFeign.findWmNewsById(newsId);
        //2.判断是否存在
        if (wmNewsById.getCode().intValue() != 0) {
            log.error(" 文章发布失败  原因:远程调用自媒体文章查询失败 {} ", wmNewsById.getErrorMessage());
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST, "未查询到自媒体文章!");
        }
        //得到自媒体文章的数据,再检查自媒体文章有没有
        WmNews wmNews = wmNewsById.getData();
        if (wmNews == null) {
            log.error(" 文章发布失败  原因:未查到自媒体文章信息,文章id {} ", newsId);
            CustException.cust(AppHttpCodeEnum.REMOTE_SERVER_ERROR, "自媒体文章不存在,远程查询自媒体文章失败!");
        }
        //3.检查状态是否为4或者8
        Short status = wmNews.getStatus();
        if (!WemediaConstants.WM_NEWS_AUTH_PASS.equals(status) && !WemediaConstants.WM_NEWS_AUTHED_STATUS.equals(status)) {
            log.info("文章发布失败     原因:文章的状态错误,状态不是8或者4,文章id {}", newsId);
            CustException.cust(AppHttpCodeEnum.DATA_NOT_ALLOW, "文章状态错误");

        }
        return wmNews;
    }

    @Autowired
    private ApArticleMapper apArticleMapper;
    @Value("${file.oss.web-site}")
    private String webSite;

    @Value("${file.minio.readPath}")
    String readPath;
    /**
     * 根据参数加载文章列表
     * @param loadtype 1为加载更多  2为加载最新
     * @param dto
     * @return
     */
    @Override
    public ResponseResult load(Short loadtype, ArticleHomeDTO dto) {
        //1 参数检查
        // 分页大小,没有给传的话就默认设置10
        Integer size = dto.getSize();
        if (size == null || size <= 0) {
            size = 10;
        }
        dto.setSize(size);
        // 频道
        if (StringUtils.isBlank(dto.getTag())) {
            dto.setTag(ArticleConstants.DEFAULT_TAG);
        }
        // 时间:最大时间和最小时间
        if (dto.getMaxBehotTime() == null) {
            dto.setMaxBehotTime(new Date());
        }
        if (dto.getMinBehotTime() == null) {
            dto.setMinBehotTime(new Date());
        }
        // 类型判断
        if (!loadtype.equals(ArticleConstants.LOADTYPE_LOAD_MORE) && !loadtype.equals(ArticleConstants.LOADTYPE_LOAD_NEW)) {
            loadtype = ArticleConstants.LOADTYPE_LOAD_MORE;
        }
        //2 调用mapper执行查询
        List<ApArticle> articleList = apArticleMapper.loadArticleList(dto, loadtype);
        // 添加静态页面访问前缀
        for (ApArticle apArticle : articleList) {
            apArticle.setStaticUrl(readPath + apArticle.getStaticUrl());
        }
        //3 返回结果
        ResponseResult result = ResponseResult.okResult(articleList);
        result.setHost(webSite);
        return result;
    }
}